package com.zyf.chapter02.structure.decorator.eureka;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 重定向客户端
 * @author yifeng
 */
public class RedirectingHttpClient extends HttpClientDecorator {
    private TransportClientFactory clientFactory;

    private AtomicReference<HttpClient> delegateRef = new AtomicReference<>();

    RedirectingHttpClient(TransportClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }

    @Override
    protected String execute(RequestExecutor executor) {
        System.out.println("Redirecting 执行 execute 逻辑");
        if (delegateRef.get() == null) {
            delegateRef.set(clientFactory.newClient());
        }
        return executor.execute(delegateRef.get());
    }

    public static TransportClientFactory createFactory(TransportClientFactory factory) {
        return () -> new RedirectingHttpClient(factory);
    }

}
